/**
 *
 */
package com.angel.io.validators.impl;

import java.lang.reflect.Method;

import com.angel.common.helpers.AnnotationHelper;
import com.angel.common.helpers.ReflectionHelper;
import com.angel.common.helpers.StringHelper;
import com.angel.io.annotations.ColumnRow;
import com.angel.io.annotations.RowProcessor;
import com.angel.io.annotations.RowProcessorCommand;
import com.angel.io.exceptions.RowProcessorCommandValidatorException;
import com.angel.io.helpers.Helper;
import com.angel.io.type.rows.ImportRowFile;
import com.angel.io.type.rows.impl.HeaderRowFile;
import com.angel.io.validators.RowProcessorCommandValidator;

/**
 * @author William
 *
 */
public class ColumnsParametersRowProcessorAnnotationValidator implements RowProcessorCommandValidator{

	public void validate(Class<?> importRowCommandClass) throws RowProcessorCommandValidatorException {
		boolean hasAnnotation = AnnotationHelper.hasAnnotation(importRowCommandClass, RowProcessorCommand.class);
		if(hasAnnotation){
			RowProcessorCommand rowProcessorCommand = AnnotationHelper.getAnnotation(importRowCommandClass, RowProcessorCommand.class);
			Method rowProcessorMethod = ReflectionHelper.getAllMethodWith(RowProcessor.class, importRowCommandClass)[0];
			RowProcessor rowProcessor = AnnotationHelper.getAnnotation(rowProcessorMethod, RowProcessor.class);

			ColumnRow[] columnRows = rowProcessorCommand.columnsRow();
			Class<?>[] methodTypeParameters = new Class<?>[Helper.calculateQuantityParameters(rowProcessor, rowProcessorCommand.columnsRow().length)];
			int currentPosition = 0;
			if(rowProcessor.importRow()){
				methodTypeParameters[currentPosition] = ImportRowFile.class;
				currentPosition++;
			}
			if(rowProcessor.headerRow()){
				methodTypeParameters[currentPosition] = HeaderRowFile.class;
				currentPosition++;
			}
			if(!rowProcessor.object().equals(Object.class)){
				methodTypeParameters[currentPosition] = rowProcessor.object();
				currentPosition++;
			}
			if(rowProcessor.columnsParameters().length ==0){
				for(ColumnRow cr: rowProcessorCommand.columnsRow()){
					methodTypeParameters[currentPosition] = cr.type();
					currentPosition++;
				}
			} else {
				for(int pos: rowProcessor.columnsParameters()){
					methodTypeParameters[currentPosition] = columnRows[pos].type();
					currentPosition++;
				}
			}
			boolean matchs = ReflectionHelper.matchParametersTypes(rowProcessorMethod, methodTypeParameters);
			if(!matchs){
				throw new RowProcessorCommandValidatorException("Row processor method's parameters [" + rowProcessorMethod.getName() + "] at class [" + importRowCommandClass.getName() + "] doesn't match " +
						"	with parameters [" + StringHelper.convertToPlainString(methodTypeParameters, ",") + "].");
			}
		}
	}


}
